package lore.miniwechat.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import lore.miniwechat.dto.BaseResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoreAuthenticationFailureHandler implements AuthenticationFailureHandler {
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        BaseResponse response = new BaseResponse();
        response.setCode(HttpStatus.UNAUTHORIZED.value() + "");
        response.setMessage("登录失败！");

        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(response);

        // 防止中文乱码
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().write(s);

    }
}
